<template>
  <div class="rental-process">
    <el-card class="process-card">
      <template #header>
        <div class="card-header">
          <h3>租车流程</h3>
          <el-steps :active="currentStep" finish-status="success">
            <el-step title="选择日期"></el-step>
            <el-step title="确认订单"></el-step>
            <el-step title="支付"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>
        </div>
      </template>

      <!-- 步骤1：选择日期 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="car-info">
          <el-row :gutter="20">
            <el-col :span="8">
<!--              <img :src="carInfo.imageUrl || '/default-car.jpg'" alt="车辆图片" class="car-image">-->
              <img :src="`/api/file/download.do?filename=${carInfo.imageUrl}`"
                   :alt="车辆图片" class="car-image" />
            </el-col>
            <el-col :span="16">
              <h4>{{ carInfo.brand }} {{ carInfo.model }}</h4>
              <p class="car-details">
                <span>车牌号：{{ carInfo.licensePlate }}</span>
                <span>日租金：<span class="price">¥{{ carInfo.dailyRent }}/天</span></span>
              </p>
            </el-col>
          </el-row>
        </div>

        <el-divider></el-divider>

        <div class="date-selection">
          <h4>选择租车日期</h4>

          <!-- 可租日期提示 -->
          <div v-if="unavailableDates.length > 0" class="availability-notice">
            <el-alert
              title="日期提醒"
              type="info"
              :closable="false"
              show-icon>
              <template #default>
                <p>该车辆已被预订的日期将无法选择，请选择其他可用日期。</p>
                <p v-if="unavailableDates.length <= 10">
                  不可租日期：{{ unavailableDates.join(', ') }}
                </p>
                <p v-else>
                  共有 {{ unavailableDates.length }} 个不可租日期
                </p>
              </template>
            </el-alert>
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="取车日期">
                <el-date-picker
                  v-model="rentalForm.startDate"
                  type="date"
                  placeholder="选择取车日期"
                  :disabled-date="disabledStartDate"
                  @change="calculateCost"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="还车日期">
                <el-date-picker
                  v-model="rentalForm.endDate"
                  type="date"
                  placeholder="选择还车日期"
                  :disabled-date="disabledEndDate"
                  @change="calculateCost"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if="costInfo.days > 0" class="cost-summary">
            <el-card class="cost-card">
              <h4>费用明细</h4>
              <div class="cost-item">
                <span>租车天数：</span>
                <span>{{ costInfo.days }} 天</span>
              </div>
              <div class="cost-item">
                <span>日租金：</span>
                <span>¥{{ costInfo.dailyRent }}/天</span>
              </div>
              <el-divider></el-divider>
              <div class="cost-item total">
                <span>总费用：</span>
                <span class="total-amount">¥{{ costInfo.totalAmount }}</span>
              </div>
            </el-card>
          </div>
        </div>

        <div class="step-actions">
          <el-button @click="$router.back()">返回</el-button>
          <el-button type="primary" @click="nextStep" :disabled="!canProceed">下一步</el-button>
        </div>
      </div>

      <!-- 步骤2：确认订单 -->
      <div v-if="currentStep === 1" class="step-content">
        <div class="order-summary">
          <h4>订单确认</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="车辆信息">{{ carInfo.brand }} {{ carInfo.model }}</el-descriptions-item>
            <el-descriptions-item label="车牌号">{{ carInfo.licensePlate }}</el-descriptions-item>
            <el-descriptions-item label="取车日期">{{ formatDate(rentalForm.startDate) }}</el-descriptions-item>
            <el-descriptions-item label="还车日期">{{ formatDate(rentalForm.endDate) }}</el-descriptions-item>
            <el-descriptions-item label="租车天数">{{ costInfo.days }} 天</el-descriptions-item>
            <el-descriptions-item label="日租金">¥{{ costInfo.dailyRent }}/天</el-descriptions-item>
            <el-descriptions-item label="总费用" class="total-row">
              <span class="total-amount">¥{{ costInfo.totalAmount }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="createOrder" :loading="creating">确认订单</el-button>
        </div>
      </div>

      <!-- 步骤3：支付 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="payment-section">
          <h4>选择支付方式</h4>
          <el-radio-group v-model="selectedPaymentMethod" class="payment-methods">
            <div class="payment-option-wrapper" :class="{ 'selected': selectedPaymentMethod === '1' }">
              <el-radio label="1">
                <div class="payment-item">
                  <el-icon class="payment-icon wechat" size="24">
                    <ChatDotRound />
                  </el-icon>
                  <span>微信支付</span>
                </div>
              </el-radio>
            </div>
            <div class="payment-option-wrapper" :class="{ 'selected': selectedPaymentMethod === '2' }">
              <el-radio label="2">
                <div class="payment-item">
                  <el-icon class="payment-icon alipay" size="24">
                    <CreditCard />
                  </el-icon>
                  <span>支付宝</span>
                </div>
              </el-radio>
            </div>
          </el-radio-group>

          <div class="payment-amount">
            <h4>支付金额：<span class="amount">¥{{ costInfo.totalAmount }}</span></h4>
          </div>
        </div>

        <div class="step-actions">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="processPayment" :loading="paying">支付</el-button>
        </div>
      </div>

      <!-- 步骤4：完成 -->
      <div v-if="currentStep === 3" class="step-content">
        <div class="success-content">
          <el-result icon="success" title="租车成功！" sub-title="您的租车订单已创建成功">
            <template #extra>
              <div class="order-info">
                <p>订单号：{{ orderInfo.id }}</p>
                <p>请按时取车，祝您用车愉快！</p>
              </div>
              <div class="action-buttons">
                <el-button type="primary" @click="goToOrders">我的订单</el-button>
                <el-button @click="goToBrowse">继续浏览</el-button>
              </div>
            </template>
          </el-result>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ChatDotRound, CreditCard } from '@element-plus/icons-vue'
import { calculateRentalCost, createRental } from '@/api/rental'
import { simulatePayment } from '@/api/paymentSimulation'
import { getCarDetail, getCarAvailability } from '@/api/car'
import { useUserInfoStore } from '@/stores/userInfo'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()

// 当前步骤
const currentStep = ref(0)

// 车辆信息
const carInfo = reactive({
  id: route.params.carId,
  brand: '',
  model: '',
  licensePlate: '',
  dailyRent: 0,
  imageUrl: ''
})

// 租车表单
const rentalForm = reactive({
  startDate: '',
  endDate: ''
})

// 费用信息
const costInfo = reactive({
  days: 0,
  dailyRent: 0,
  totalAmount: 0
})

// 订单信息
const orderInfo = reactive({
  id: null
})

// 支付相关
const selectedPaymentMethod = ref('1')
const creating = ref(false)
const paying = ref(false)

// 车辆可用性
const unavailableDates = ref([])
const loading = ref(false)

// 计算属性
const canProceed = computed(() => {
  return rentalForm.startDate && rentalForm.endDate && costInfo.days > 0
})

// 禁用日期函数 - 暂时简化，只禁用过去的日期
const disabledStartDate = (time) => {
  // 只禁用过去的日期，暂时不检查不可租日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const disabledEndDate = (time) => {
  if (!rentalForm.startDate) return true

  // 只禁用开始日期之前的日期
  return time.getTime() <= new Date(rentalForm.startDate).getTime()
}

// 方法
const calculateCost = async () => {
  if (!rentalForm.startDate || !rentalForm.endDate) return

  try {
    const response = await calculateRentalCost({
      startDate: formatDate(rentalForm.startDate),
      endDate: formatDate(rentalForm.endDate),
      dailyRent: carInfo.dailyRent
    })

    // 请求拦截器已经处理了响应，直接使用response.data
    if (response.code === 200) {
      Object.assign(costInfo, response.data)
      console.log('费用计算成功:', costInfo)
    } else {
      console.error('费用计算失败:', response.msg)
    }
  } catch (error) {
    console.error('费用计算API调用失败:', error)

    // 后端API调用失败时，使用本地计算作为备用
    const startDate = new Date(rentalForm.startDate)
    const endDate = new Date(rentalForm.endDate)
    const timeDiff = endDate.getTime() - startDate.getTime()
    const days = Math.ceil(timeDiff / (1000 * 3600 * 24))

    if (days > 0) {
      const dailyRent = carInfo.dailyRent || 180
      const totalAmount = days * dailyRent

      Object.assign(costInfo, {
        days: days,
        dailyRent: dailyRent,
        totalAmount: totalAmount
      })

      console.log('使用本地计算结果:', costInfo)
    }
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0')
}

const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const createOrder = async () => {
  creating.value = true

  try {
    const response = await createRental({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      carId: carInfo.id,
      startDate: formatDate(rentalForm.startDate),
      endDate: formatDate(rentalForm.endDate),
      dailyRent: carInfo.dailyRent
    })

    // 修正响应数据处理逻辑
    if (response.code === 200) {
      orderInfo.id = response.data.id
      ElMessage.success('订单创建成功')
      console.log('订单创建成功，订单ID:', orderInfo.id)
      nextStep()
    } else {
      ElMessage.error(response.msg || '订单创建失败')
    }
  } catch (error) {
    console.error('后端订单创建失败，使用模拟订单:', error)

    // 后端API失败时，生成模拟订单ID
    orderInfo.id = 'DEMO_' + Date.now()
    ElMessage.success('订单创建成功（演示模式）')
    nextStep()
  } finally {
    creating.value = false
  }
}

const processPayment = async () => {
  paying.value = true

  try {
    const response = await simulatePayment({
      orderId: orderInfo.id,
      userId: userInfoStore.userInfo?.id || '1', // 从用户状态获取真实用户ID
      paymentType: selectedPaymentMethod.value,
      amount: costInfo.totalAmount
    })

    // 修正响应数据处理逻辑
    if (response.code === 200 && response.data.success) {
      ElMessage.success('支付成功！')
      nextStep()
    } else {
      ElMessage.error(response.data?.message || response.msg || '支付失败')
    }
  } catch (error) {
    console.error('后端支付失败，使用模拟支付:', error)

    // 模拟支付成功
    ElMessage.success('支付成功！（演示模式）')
    nextStep()
  } finally {
    paying.value = false
  }
}

const goToOrders = () => {
  router.push('/user/rental/orders')
}

const goToBrowse = () => {
  router.push('/user/carBrowse')
}

// 初始化
// 加载车辆信息
const loadCarInfo = async () => {
  try {
    loading.value = true
    const carId = route.params.carId

    console.log('开始加载车辆信息，carId:', carId)
    console.log('当前路由参数:', route.params)

    if (!carId) {
      ElMessage.error('车辆ID参数缺失')
      return
    }

    // 获取车辆详情
    const carRes = await getCarDetail(carId)
    const carData = carRes.data

    console.log('获取到的车辆数据:', carData)

    carInfo.brand = carData.brand || ''
    carInfo.model = carData.model || ''
    carInfo.licensePlate = carData.licensePlate || ''
    carInfo.dailyRent = carData.dailyRent || 0
    carInfo.imageUrl = carData.images || ''

    // 获取车辆可用性
    const availabilityRes = await getCarAvailability(carId)
    unavailableDates.value = availabilityRes.data || []

    console.log('车辆信息加载完成:', carInfo)
    console.log('不可租日期:', unavailableDates.value)
    console.log('不可租日期数量:', unavailableDates.value.length)

  } catch (error) {
    console.error('加载车辆信息失败:', error)
    ElMessage.error('加载车辆信息失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadCarInfo()
})
</script>

<style scoped>
.rental-process {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.process-card {
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.step-content {
  padding: 20px 0;
}

.car-info {
  margin-bottom: 30px;
}

.car-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
}

.car-details {
  margin-top: 10px;
}

.car-details span {
  display: block;
  margin-bottom: 5px;
  color: #606266;
}

.price {
  color: #e6a23c;
  font-weight: bold;
}

.date-selection h4 {
  margin-bottom: 20px;
  color: #303133;
}

.availability-notice {
  margin: 15px 0;
}

.availability-notice p {
  margin: 5px 0;
  font-size: 14px;
}

.cost-summary {
  margin-top: 30px;
}

.cost-card {
  background: #f8f9fa;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.cost-item.total {
  font-weight: bold;
  font-size: 16px;
}

.total-amount {
  color: #e6a23c;
  font-size: 18px;
  font-weight: bold;
}

.step-actions {
  margin-top: 30px;
  text-align: right;
}

.step-actions .el-button {
  margin-left: 10px;
  min-width: 100px;
  height: 40px;
}

.order-summary h4 {
  margin-bottom: 20px;
  color: #303133;
}

.payment-section h4 {
  margin-bottom: 20px;
  color: #303133;
}

.payment-methods {
  margin-bottom: 30px;
  display: flex;
  flex-direction: row;
  gap: 20px;
  justify-content: center;
}

.payment-option-wrapper {
  border: 2px solid #dcdfe6;
  border-radius: 12px;
  padding: 15px;
  transition: all 0.3s ease;
  background: #fff;
  cursor: pointer;
  flex: 1;
  max-width: 200px;
  min-width: 150px;
}

.payment-option-wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.payment-option-wrapper.selected {
  border-color: #409eff !important;
  background: #f0f9ff !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2) !important;
}

.payment-methods .el-radio {
  width: 100%;
  margin: 0;
  height: auto;
}

.payment-methods .el-radio__input {
  position: absolute;
  top: 15px;
  right: 15px;
}

.payment-methods .el-radio__label {
  width: 100%;
  padding: 0;
  display: block;
}

.payment-item {
  display: flex;
  align-items: center;
}

.payment-icon {
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon.wechat {
  color: #07c160;
}

.payment-icon.alipay {
  color: #1677ff;
}

.payment-amount {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.payment-amount .amount {
  color: #e6a23c;
  font-size: 24px;
  font-weight: bold;
}

.success-content {
  text-align: center;
}

.order-info {
  margin: 20px 0;
}

.order-info p {
  margin: 10px 0;
  color: #606266;
}

.action-buttons {
  margin-top: 20px;
}

.action-buttons .el-button {
  margin: 0 10px;
  min-width: 100px;
  height: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-methods {
    flex-direction: column;
    gap: 15px;
  }

  .payment-option-wrapper {
    max-width: none;
    min-width: auto;
  }
}
</style>
